import 'package:flutter/material.dart';

import 'package:hzy_normal_tool/hzy_normal_tool.dart';

import '../../common/index.dart';
import '../../models/index.dart';

class DetailImageLongWidget extends StatefulWidget {
  const DetailImageLongWidget({
    super.key,
    required this.imageList,
    this.scrollStar,
    this.scrollUpdata,
    this.scrollEnd,
    this.userScroll,
    this.scrollerIndex,
  });

  /// 滚动下标回调
  final Function(int index)? scrollerIndex;

  /// 滑动开始
  final Function(ScrollNotification notification)? scrollStar;

  /// 滑动中
  final Function(ScrollNotification notification)? scrollUpdata;

  /// 滑动结束
  final Function(ScrollNotification notification)? scrollEnd;

  /// 用户主动滑动结束
  final Function(ScrollNotification notification)? userScroll;

  /// 图片列表
  final List<ImageNormalModel> imageList;
  @override
  State<StatefulWidget> createState() {
    return DetailImageLongWidgetState();
  }
}

class DetailImageLongWidgetState
    extends BaseStateWidget<DetailImageLongWidget> {
  // --------- 公开属性  --------- //

  // --------- 私有属性  --------- //
  /// 图片个数
  int num = 0;

  /// 最大高度
  double maxh = 0;

  /// 滚动控制器
  ScrollController scrollController = ScrollController(initialScrollOffset: 0);

  /// 界面子视图列表
  List<Widget> list = [];

  /// 图片尺寸列表
  List sizeList = [];

  /// 当前下标信息
  Map currentInfo = {
    "index": 0,
    "star": 0.0,
    "end": 0.0,
  };

  /// 是否是用户滚动
  bool isUserScroller = true;
  // --------- 生命周期  --------- //
  @override
  void initState() {
    scrollController = ScrollController();
    list = createListImage();
    super.initState();
  }

  @override
  void didUpdateWidget(covariant DetailImageLongWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    debugLog("didUpdateWidget");
  }

  @override
  void dispose() {
    scrollController.dispose();
    super.dispose();
  }

  // --------- 构建UI  --------- //

  @override
  Widget createBody({
    required BuildContext context,
    BoxConstraints? constraints,
  }) {
    Widget body = SingleChildScrollView(
      controller: scrollController,
      child: Column(
        children: list,
      ),
    );

    body = Scrollbar(
      notificationPredicate: (notification) {
        configNotification(notification: notification);
        return true;
      },
      controller: scrollController,
      child: body,
    );
    return body;
  }

  // 创建图片数组
  createListImage() {
    List<Widget> list = [];
    num = widget.imageList.length;
    for (var i = 0; i < num; i++) {
      list.add(createItemBuilder(context, i));
    }
    return list;
  }

  // 创建单个图片视图
  Widget createItemBuilder(BuildContext context, int index) {
    ImageNormalModel imageNormalModel = widget.imageList[index];
    double star = maxh;
    maxh = maxh + (imageNormalModel.size?.height ?? 0);
    Map info = {
      "index": index,
      "star": star,
      "end": maxh,
    };
    sizeList.add(info);
    return Image.network(
      imageNormalModel.url ?? "",
      fit: BoxFit.cover,
      width: imageNormalModel.size?.width,
      height: imageNormalModel.size?.height,
    );
  }

  // --------- 数据处理  --------- //

  // --------- 触发事件  --------- //

  configNotification({required ScrollNotification notification}) {
    //1.监听事件的类型
    if (notification is ScrollStartNotification) {
      debugLog("开始滑动");
      configScrollStar(notification: notification);
    } else if (notification is ScrollUpdateNotification) {
      //当前滚动的位置和总长度
      configScrollUpdate(notification: notification);
    } else if (notification is OverscrollNotification) {
      debugLog("OverscrollNotification");
    } else if (notification is ScrollEndNotification) {
      debugLog("滑动停止");
      configScrollEnd(notification: notification);
    } else if (notification is UserScrollNotification) {
      debugLog("UserScrollNotification");
      configUserScroll(notification: notification);
    }
  }

  /// 滚动开始
  configScrollStar({required ScrollNotification notification}) {
    if (widget.scrollStar != null) {
      widget.scrollStar!(notification);
    }
  }

  /// 滑动中
  configScrollUpdate({required ScrollNotification notification}) {
    final currentPixel = notification.metrics.pixels;
    final totalPixel = notification.metrics.maxScrollExtent;
    int index = configScrollerHeightWithIndex(pixels: currentPixel);
    double bottomM = (totalPixel - (100));
    if (scrollController.position.pixels > bottomM) {
      index = num - 1;
    }
    if (widget.scrollUpdata != null) {
      widget.scrollUpdata!(notification);
    }
    if (widget.scrollerIndex != null && isUserScroller) {
      widget.scrollerIndex!(index);
    }
  }

  /// 滑动结束
  configScrollEnd({required ScrollNotification notification}) {
    if (widget.scrollEnd != null) {
      widget.scrollEnd!(notification);
    }
  }

  /// 用户滑动有距离后停止
  configUserScroll({required ScrollNotification notification}) {
    isUserScroller = true;
    if (widget.userScroll != null) {
      widget.userScroll!(notification);
    }
  }

  /// 根据图片 大小  获取 滚动距离
  configScrollerJumpToHeight({
    required int index,
  }) {
    double jumptoheight = 0;
    for (var i = 0; i < index; i++) {
      ImageNormalModel imageNormalModel = widget.imageList[i];
      jumptoheight = jumptoheight + (imageNormalModel.size?.height ?? 0);
    }
    return jumptoheight;
  }

  /// 对外公开跳转到指定的下标
  configLongImageSjumpToIndex({
    required int index,
  }) {
    double jumpH = configScrollerJumpToHeight(index: index);
    if (index == num - 1) {
      jumpH = scrollController.position.maxScrollExtent;
    }
    isUserScroller = false;
    scrollController.jumpTo(jumpH);
  }

  /// 根据滑动距离，获取当前下标
  configScrollerHeightWithIndex({required double pixels}) {
    double star = currentInfo["star"];
    double end = currentInfo["end"];
    if (pixels > star && pixels <= end) {
      return currentInfo["index"];
    }
    int rIndex = 0;
    for (var element in sizeList) {
      double xStar = element["star"];
      double xEnd = element["end"];
      int xIndex = element["index"];
      if (pixels > xStar && pixels <= xEnd) {
        currentInfo = element;
        rIndex = xIndex;
        break;
      }
    }

    return rIndex;
  }

  updataImageList() {
    setState(() {
      list = createListImage();
    });
  }
}
